<template>
  <el-container>
    <!-- 头部区域 -->
    <el-header style="display: flex; justify-content: space-between; align-items: center;">
      <div>毛孩乐园</div>
      <div style="display: flex; align-items: center;">
        <el-dropdown style="margin-right: 20px;">
          <span class="el-dropdown-link">
            <i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item icon="el-icon-user">个人主页</el-dropdown-item>
            <el-dropdown-item icon="el-icon-switch-button">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-avatar :size="40" :src="circleUrl"></el-avatar>
      </div>
    </el-header>
    <!-- 主体区域 -->
    <el-container>
      <!-- 侧边栏菜单 -->
      <el-aside style="width: 200px; background-color: #f2f2f2;">
        <el-menu default-active="6" class="el-menu-vertical-demo">
          <template v-if="userType === '02'">
            <router-link to="/goods">
              <el-menu-item index="2">
                <i class="el-icon-goods"></i>
                <template slot="title">商品管理</template>
              </el-menu-item>
            </router-link>
            <router-link to="/video">
              <el-menu-item index="4">
                <i class="el-icon-video-camera"></i>
                <template slot="title">视频管理</template>
              </el-menu-item>
            </router-link>
            <router-link to="/order">
              <el-menu-item index="5">
                <i class="el-icon-tickets"></i>
                <template slot="title">订单管理</template>
              </el-menu-item>
            </router-link>
            <router-link to="/statistics">
              <el-menu-item index="6">
                <i class="el-icon-data-analysis"></i>
                <template slot="title">统计数据</template>
              </el-menu-item>
            </router-link>
          </template>
          <template v-else>
            <router-link to="/shop">
              <el-menu-item index="1">
                <i class="el-icon-takeaway-box"></i>
                <template slot="title">商店管理</template>
              </el-menu-item>
            </router-link>
            <router-link to="/goods">
              <el-menu-item index="2">
                <i class="el-icon-goods"></i>
                <template slot="title">商品管理</template>
              </el-menu-item>
            </router-link>
            <router-link to="/user">
              <el-menu-item index="3">
                <i class="el-icon-user"></i>
                <template slot="title">会员管理</template>
              </el-menu-item>
            </router-link>
          </template>
        </el-menu>
      </el-aside>
      <!-- 主要内容区域 -->
      <el-main>
        <!-- 总览卡片 -->
        <div class="overview-cards">
          <el-card shadow="hover" style="flex: 1; margin-right: 20px;">
            <div slot="header">销售总额</div>
            <div>{{ totalSales }}</div>
          </el-card>
          <el-card shadow="hover" style="flex: 1;">
            <div slot="header">销售数量</div>
            <div>{{ totalQuantity }}</div>
          </el-card>
        </div>
        <!-- 图表类型选择 -->
        <div style="margin-bottom: 20px;">
          <el-select v-model="selectedChartType" placeholder="请选择图表类型" @change="updateChart">
            <el-option label="折线图" value="line"></el-option>
            <el-option label="柱状图" value="bar"></el-option>
            <el-option label="饼图" value="pie"></el-option>
          </el-select>
        </div>
        <!-- 图表 -->
        <div ref="chartsContainer" class="chart-container"></div>
        <!-- 导出按钮 -->
        <el-button type="primary" icon="el-icon-download" @click="exportData">导出数据</el-button>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import * as echarts from 'echarts';
import request from "@/utils/request";

export default {
  data() {
    return {
      circleUrl: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
      totalSales: 0,
      totalQuantity: 0,
      salesData: [],
      userType: localStorage.getItem('userType'),
      shopId: localStorage.getItem('shopId'),
      chart: null,
      selectedChartType: 'line' // 默认图表类型
    };
  },
  mounted() {
    this.loadSalesData();
    // 初始化图表
    this.chart = echarts.init(this.$refs.chartsContainer);
  },
  methods: {
    async loadSalesData() {
      try {
        const response = await request.get(`/goods/statistics?shopId=${this.shopId}`);
        this.salesData = response.data;

        // 计算总销售额和总销售数量
        this.totalSales = this.salesData.reduce((acc, item) => acc + item.price * item.goodsCount, 0);
        this.totalQuantity = this.salesData.reduce((acc, item) => acc + item.goodsCount, 0);

        // 初始更新图表数据
        this.updateChart();
      } catch (error) {
        console.error('Error loading sales data:', error);
      }
    },
    updateChart() {
      let option = {};

      if (this.selectedChartType === 'line' || this.selectedChartType === 'bar') {
        option = {
          title: {
            text: '销售趋势'
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['近一周', '近一个月', '近一年']
          },
          xAxis: {
            type: 'category',
            boundaryGap: this.selectedChartType === 'bar',
            data: this.salesData.map(item => item.goodsName)
          },
          yAxis: {
            type: 'value'
          },
          series: ['weekSales', 'monthSales', 'yearSales'].map((type, index) => ({
            name: this.getSeriesNameByIndex(index),
            type: this.selectedChartType,
            data: this.salesData.map(item => item[type])
          }))
        };
      } else if (this.selectedChartType === 'pie') {
        option = {
          title: {
            text: '销售饼图'
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [
            {
              name: '销售数据',
              type: 'pie',
              radius: '50%',
              data: this.salesData.map(item => ({
                name: item.goodsName,
                value: item.yearSales // 或者其他需要展示的指标
              }))
            }
          ]
        };
      }

      this.chart.clear();
      this.chart.setOption(option);
    },
    getSeriesNameByIndex(index) {
      const names = ['近一周', '近一个月', '近一年'];
      return names[index] || '';
    },
    exportData() {
      const csvContent = [
        ['商品ID', '商品名', '价格', '总数', '近一周销量', '近一个月销量', '近一年销量'],
        ...this.salesData.map(item => [item.goodsId, item.goodsName, item.price, item.goodsCount, item.weekSales, item.monthSales, item.yearSales])
      ].map(e => e.join(",")).join("\n");

      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = 'sales_data.csv';
      link.click();
    },
    logout() {
      localStorage.removeItem('userType');
      localStorage.removeItem('shopId');
      this.$router.push('/login');
    }
  },
  watch: {
    salesData() {
      if (this.chart) {
        this.updateChart();
      }
    }
  }
};
</script>

<style scoped>
.el-header {
  text-align: initial;
  border: 1px solid black;
  display: flex;
  align-items: center;
  font-size: 20px;
  font-weight:bold;
}

.el-aside{
  background-color: rgb(238, 241, 246);
  width:150px;
  height: auto;
  border:1px solid black;

}
.el-main{
  border:1px solid black;

}

.overview-cards {
  display: flex;
  margin-bottom: 20px;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.el-button {
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 20px;
}
</style>
